package com.zhai.domain.award.service.distribute.impl;

import cn.hutool.core.util.StrUtil;
import com.zhai.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.zhai.domain.award.model.entity.DistributeAwardEntity;
import com.zhai.domain.award.model.entity.UserAwardRecordEntity;
import com.zhai.domain.award.model.entity.UserCreditAwardEntity;
import com.zhai.domain.award.model.valobj.AwardStateVO;
import com.zhai.domain.award.repository.IAwardRepository;
import com.zhai.domain.award.service.distribute.IDistributeAward;
import com.zhai.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @Description: 用户随机积分奖品发放服务
 * @ClassName: UserCreditRandomAward
 * @Author: zhaiyongxin
 * @Date: 2025/6/23 10:45
 * @Version: 1.0
 */
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {

    @Resource
    private IAwardRepository awardRepository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        /**
         * 积分发奖
         * 1. 优先使用奖品透传过来的积分奖品配置
         * 2. 如未配置积分奖品配置 则使用奖品自带的积分配置
         */
        String userId = distributeAwardEntity.getUserId();
        Integer awardId = distributeAwardEntity.getAwardId();
        String awardConfig = distributeAwardEntity.getAwardConfig();
        if (StrUtil.isBlank(awardConfig)) {
            // 查询奖品对应的积分配置
            awardConfig = awardRepository.queryAwardConfigByAwardId(awardId);
        }
        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if (creditRange.length != 2) {
            throw new RuntimeException("award_config 「" + awardConfig + "」配置不是一个范围值，如 1,100");
        }
        // 生成随机积分值
        BigDecimal creditAmount = generateRandom(new BigDecimal(creditRange[0]), new BigDecimal(creditRange[1]));

        //生成聚合对象
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buildUserAwardRecordEntity(userId, distributeAwardEntity.getOrderId(), distributeAwardEntity.getAwardId(), AwardStateVO.complete);
        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(userId, creditAmount);
        GiveOutPrizesAggregate giveOutPrizesAggregate = GiveOutPrizesAggregate.builder()
                .userId(userId)
                .userCreditAward(userCreditAwardEntity)
                .userAwardRecord(userAwardRecordEntity)
                .build();

        // 存储发奖对象
        awardRepository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);


    }

    private BigDecimal generateRandom(BigDecimal min, BigDecimal max) {
        if (min.equals(max)) return min;
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3));
    }
}
